<?php 
if (! defined('BASEPATH')) {
    exit('Access Denied');
}

/*
*author wangjian
*time 2013-03-16
*/
class Index extends MY_Controller {
	private $username ;//登录的用户
	private $admin ;//创始人
	private $group_name ;//群组
	private  $ip  ;//登录的ip地址
	private $table_ ; //表的前缀
	private $maxsize = 0 ;
	private $allowed_types = "*";
	private $upload_path = "./uploads/";
    function Index(){
        parent::__construct();
		$this->load->library('admin_common');//加载admin的公用方法
		$this->load->library('session');//加载session
		$this->username = $this->get_login_name(); //得到登录的用户名
		$this->load->model('admin/upload/M_upload');
		$this->admin = $this->config->item('web_admin_master');//创始人
		$this->group_name = ($this->admin == $this->username)?'管理员':($this->admin_common->group_name());
		$this->ip = $this->admin_common->get_client_ip();
		$this->table_ = $this->admin_common->table_pre('real_data');
    }
    //上传文件列表
    function filelist(){     
    	$this->load->library('pagination');//加载分页类
		$this->load->library('MY_Pagination');//加载分页类
		$post_data = $this->input->post(NULL,true) ; 
		$is_search = '' ;
		
		if(isset($post_data['is_search']) && $post_data['is_search'] == 'search'){
			$this->search() ;
		}else{
			 $this->load->view('admin/upload/views_filelist');
		}        
    }
	private function search(){
		$post_data = $this->input->post(NULL,true) ;
		$where = ' where 1=1';
		
		/*$allow_admin = $post_data['allowadmin'];
		if($allow_admin != 'all'){
			
			$where.=' AND `allowadmin`='.intval($allow_admin);
		}*/
		if(isset($post_data['filename'])){
			$filename = $this->admin_common->do_addslashes($post_data['filename']);
		}	
				
		if(!empty($filename)){
			$where.=" AND filename like '%{$filename}%'";
		}
		
	
		if(!isset($post_data['page'])){
			$page  =1 ;
		}else{
			$page = intval($post_data['page']);
		}		

		$sql_count = "SELECT count(*) as tt FROM {$this->table_}extra_filelist ".$where;
		
		$total = $this->M_upload->query_count($sql_count);
 		$per_page = 10;//每一页显示的数量
		$page_string = $this->page_string($total, $per_page, $page);

     	
		$limit = ($page-1)*$per_page;
		$sql = "SELECT * FROM {$this->table_}extra_filelist $where ORDER BY id DESC  LIMIT ".$limit.",".$per_page;
		
		$res = $this->M_upload->querylist($sql);
		if($res){
			$res = $this->admin_common->object_to_array($res);
		}
		if($res){
			foreach($res as $key=>$val){
				$res[$key]['status'] = ($val['status'] == 1 )?'有效':'<font color="red">无效</font>';
				
			}		
		}	
		
		$data['result'] = $res ;
		$data['page_string'] = $page_string ;	
		echo $this->admin_common->result_to_towf_new($data,'','',null);
	}    
    //上传文件
    function uploadfile(){
    	 $this->load->helper(array('form', 'url'));
    	$action = $this->input->get_post("action",true) ;
    	if($action == 'do'){
    		$this->do_upload() ;
    		exit();
    	}
    	$this->load->view('admin/upload/views_uploadfile');
    }
  	private function do_upload(){
  		$filename = html_escape(strip_tags($this->input->get_post("filename",true))) ;
		$remark = html_escape(strip_tags($this->input->get_post("remark",true))) ;
  		$status = intval($this->input->get_post("status",true)); //状态
  		if($filename == ""){
  			showmessage("文件名不可以为空","admin/upload/index/uploadfile",3,0);
  			exit();
  		}
		$filepath = '' ;
		$imagePath = '' ;
		if(isset($_FILES['path']['name']) && !empty($_FILES['path']['name'])){
		 $config['upload_path'] = $this->upload_path;
		 $config['allowed_types'] = $this->allowed_types;
		 $config['max_size'] = $this->maxsize;
		// $config['max_width']  = '1024';
		 //$config['max_height']  = '768';
		 $config['remove_spaces'] = true ;
		 $config['overwrite'] = true ;
		 $now = time() ;
		 $rand = rand(1,2000);
		 $config['file_name'] = $now."_".$rand;
		 $this->load->library('upload', $config);
		 $field_name = "path";
		 if ( ! $this->upload->do_upload($field_name)){
			 $error = array('error' => $this->upload->display_errors());
			 showmessage($error['error'],"admin/upload/index/uploadfile",3,0) ;
			 die();
		 }
		 $data = array('upload_data' => $this->upload->data());
		 $filepath = $data['upload_data']['file_name'];
		}
 		if(isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])){
		 $imageArray['upload_path'] = $this->upload_path;
		 $imageArray['allowed_types'] = $this->allowed_types;
		 $imageArray['max_size'] = $this->maxsize;
		// $config['max_width']  = '1024';
		 //$config['max_height']  = '768';
		 $imageArray['remove_spaces'] = true ;
		 $imageArray['overwrite'] = true ;
		 $now = time() ;
		 $rand = rand(1,2000);
		 $imageArray['file_name'] = $now."_".$rand;
		 $this->load->library('upload', $imageArray);
		 $field_name = "image";
		 if ( ! $this->upload->do_upload($field_name)){
			 $error = array('error' => $this->upload->display_errors());
			 showmessage($error['error'],"admin/upload/index/uploadfile",3,0) ;
			 die();
		 }
		 $data = array('upload_data' => $this->upload->data());
		 $imagePath = $data['upload_data']['file_name'];
		} 		
		$addtime = date("Y-m-d H:i:s",time());
		 	//$sql_ = "INSERT INTO `{$this->table_}extra_filelist`(filename,path,addtime,status)values('{$filename}','{$filepath}','{$addtime}','{$status}')" ;
		$insert_one = array(
		 	'filename'=>$filename ,
		 	'path'=>$filepath,
		 	'addtime'=>$addtime,
		 	'status'=>$status,
			'addperson'=>$this->username,
			'remark'=>$remark,
			'image'=>$imagePath
		 );
		 	
		 $num  = $this->M_upload->insert_one($insert_one);
		 if($num>=1){
		 	showmessage("上传成功","admin/upload/index/filelist",3,1) ;
		 	exit();
		 }else{
		 	showmessage("上传失败服务器繁忙","admin/upload/index/uploadfile",3,0) ;
		 	exit();
		 }
		 
  	}
  	
  	//文件编辑
  	function edit(){
  		$this->load->helper(array('form', 'url'));
  		$action = $this->input->get_post("action",true) ;
  		$id = $this->input->get_post("id",true) ;
  		if($action == 'edit_do'){
  			$this->edit_do() ;
  			die();
  		}
  		$sql_ = "SELECT * FROM `{$this->table_}extra_filelist` WHERE id = '{$id}' limit 1 " ;
  		$row = $this->M_upload->query_one($sql_);
  		if(!$row){
  			showmessage("参数传递错误","admin/upload/index/filelist",3,0);
  			die();
  		}
  		$array_data = array(
  			'info'=>$row
  		);
  		$this->load->view('admin/upload/views_fileinfo',$array_data);
  	}
  	function preview(){
  		$action = $this->input->get_post("action",true) ;
  		$id = $this->input->get_post("id",true) ;
  		if($action == 'edit_do'){
  			$this->edit_do() ;
  			die();
  		}
  		$sql_ = "SELECT * FROM `{$this->table_}extra_filelist` WHERE id = '{$id}' limit 1 " ;
  		$row = $this->M_upload->query_one($sql_);
  		if(!$row){
  			showmessage("参数传递错误","admin/upload/index/filelist",3,0);
  			die();
  		}
  		$array_data = array(
  			'info'=>$row
  		);
  		$this->load->view('admin/upload/views_preview_fileinfo',$array_data);
  	}	
  	private function edit_do(){
  	  	$filename = html_escape(strip_tags($this->input->get_post("filename",true))) ;
		$remark = html_escape(strip_tags($this->input->get_post("remark",true))) ;
  		$status = intval($this->input->get_post("status",true)); //状态
  		$id = intval($this->input->get_post("id",true)); //状态
  		$num = intval($this->input->get_post("num",true)); //状态
  		if($filename == ""){
  			showmessage("文件名不可以为空","admin/upload/index/uploadfile",3,0);
  			exit();
  		}
  		$filepath='';
		$imagePath = '' ;
  		if(isset($_FILES['path']['name']) && !empty($_FILES['path']['name'])){
	  		 $config['upload_path'] =  $this->upload_path;
			 $config['allowed_types'] =$this->allowed_types;
			 $config['max_size'] = $this->maxsize;
			// $config['max_width']  = '1024';
			// $config['max_height']  = '768';
			 $config['remove_spaces'] = true ;
			 $config['overwrite'] = true ;
			 $now = time() ;
			 $rand = rand(1,2000);
			 $config['file_name'] = $now."_".$rand;
			 $this->load->library('upload', $config);
			 $field_name = "path";
			 if ( ! $this->upload->do_upload($field_name)){
			 	$error = array('error' => $this->upload->display_errors());
			 	showmessage($error['error'],"admin/upload/index/uploadfile",3,0) ;
			 	die() ;
			 }else{
			 	$data = array('upload_data' => $this->upload->data());
			 	$filepath = $data['upload_data']['file_name'];
			 	$addtime = date("Y-m-d H:i:s",time());
			 	$sql_one = "SELECT path FROM `{$this->table_}extra_filelist` WHERE id = '{$id}'" ;
			 	$one = $this->M_upload->query_one($sql_one);
			 	if(isset($one['path']) && !empty($one['path'])){
			 		if(file_exists("./uploads/".$one['path'])){
			 			unlink("./uploads/".$one['path']);
			 		}
			 		
			 	}
			 
			 }
  		}
  		if(isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])){
	  		 $imageArray['upload_path'] =  $this->upload_path;
			 $imageArray['allowed_types'] =$this->allowed_types;
			 $imageArray['max_size'] = $this->maxsize;
			// $imageArray['max_width']  = '1024';
			 //$imageArray['max_height']  = '768';
			 $imageArray['remove_spaces'] = true ;
			 $imageArray['overwrite'] = true ;
			 $now = time() ;
			 $rand = rand(1,2000);
			 $imageArray['file_name'] = $now."_".$rand;
			 $this->load->library('upload', $imageArray);
			 $field_name = "image";
			 if ( ! $this->upload->do_upload($field_name)){
			 	$error = array('error' => $this->upload->display_errors());
			 	showmessage($error['error'],"admin/upload/index/uploadfile",3,0) ;
			 	die() ;
			 }else{
			 	$data = array('upload_data' => $this->upload->data());
			 	$imagePath = $data['upload_data']['file_name'];
			 	$addtime = date("Y-m-d H:i:s",time());
			 	$sql_one = "SELECT image FROM `{$this->table_}extra_filelist` WHERE id = '{$id}'" ;
			 	$one = $this->M_upload->query_one($sql_one);
			 	if(isset($one['image']) && !empty($one['image'])){
			 		if(file_exists("./uploads/".$one['image'])){
			 			unlink("./uploads/".$one['image']);
			 		}
			 		
			 	}
			 
			 }
  		}
		$field_filepath = '' ;
		$field_image = '' ;
		if($filepath != ''){
			$field_filepath =",path='{$filepath}'";
		}
		if($imagePath != ''){
			$field_image = ",image='{$imagePath}'";
		}
		
		
		$sql = "UPDATE `{$this->table_}extra_filelist` SET filename = '{$filename}' {$field_filepath},status = '{$status}',num = '{$num}' {$field_image},remark = '{$remark}'  where id = '{$id}'";

		$num = $this->M_upload->update_data($sql);  		
		if($num>=1){
			 showmessage("编辑成功","admin/upload/index/filelist",3,1) ;
			 exit();
		}else{
			 showmessage("编辑失败","admin/upload/index/edit?id={$id}",3,0) ;
			exit();
		}
  		
  	}
  	
	function file_del(){
		
		$post_data = $_REQUEST;
		$id = ($post_data['id']);
		$in_id = '' ;
		if($id){
			$ids = explode(",", $id);
			for($k = 0 ;$k<count($ids);$k++){
				$in_id.=intval($ids[$k]).",";
			}
		}
		$in_id = rtrim($in_id,",") ;
		if(empty($in_id)){
			echo $this->admin_common->result_to_towf_new('',0,'参数传递出错',null);
			die();
		}
		$path_array = $this->M_upload->querylist("SELECT path FROM  `{$this->table_}extra_filelist`  WHERE id in ($in_id)");
		
		if($path_array){
			foreach($path_array as $k=>$v){
				
				if(file_exists("./uploads/".$v->path)){
					unlink("./uploads/".$v->path) ;
				}
			}
		}
	
		$sql="DELETE from   `{$this->table_}extra_filelist`  WHERE id in ($in_id)";
		$num = $this->M_upload->update_data($sql);
		$code = 0 ;
		$message = '' ;
		if($num>=1){
			$code = 1 ;
			$message = '删除成功';
		//	$this->M_log->insert($sql,'log_plugin_del',$this->username,$this->ip,1,"删除插件成功"); //插入日志记录
		}else{
			$code = 0 ;
			$message= '服务器繁忙，或者地址出错' ;
			//$this->M_log->insert($sql,'log_plugin_del',$this->username,$this->ip,0,"删除插件失败"); //插入日志记录
		}
	
		echo $this->admin_common->result_to_towf_new('',$code,$message,null);
		return ;
	}
  	
    /*@function page_string
     *@分页返回数据
    *@total 总的数量
    *@page_num 每一页显示的数量
    *@page 当前是第几页数据
    */
    private function page_string($total,$page_num,$page){
    	$page_string = '' ;
    	$this->load->library('pagination');//加载分页类
    	$this->load->library('MY_Pagination');//加载分页类
    	$config['total_rows'] = $total;
    	$config['use_page_numbers'] =true; // 当前页结束样式
    	$config['per_page'] = $page_num; // 每页显示数量，为了能有更好的显示效果，我将该数值设置得较小
    	$config['full_tag_open'] = '<div class="pg">'; // 分页开始样式
    	$config['full_tag_close'] = '</div>'; // 分页结束样式
    	$config['first_link'] = '首页'; // 第一页显示
    	$config['last_link'] = '末页'; // 最后一页显示
    	$config['next_link'] = '下一页 >'; // 下一页显示
    	$config['prev_link'] = '< 上一页'; // 上一页显示
    	$config['cur_tag_open'] = ' <a class="current">'; // 当前页开始样式
    	$config['cur_tag_close'] = '</a>'; // 当前页结束样式
    	$config['uri_segment'] = 6;
    	$config['anchor_class']='class="ajax_page" ';
    	$this->pagination->cur_page = $page ;
    	$this->pagination->initialize($config); // 配置分页
    	$page_string =  $this->pagination->create_links(true,'ajax_data');
    	return $page_string ;
    }    

    
}

/* End of file index.php */
/* Location: ./application/controllers/index.php */